import { GameMode, Player } from "@minecraft/server";
import { Game, GameComponent } from "@sapi-game/main";
import { Vector3Utils } from "@sapi-game/utils";
import { EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { PKParkourState } from "../pkParkourState";
import { PKItemStoreComponent } from "./itemStrore";

export class PKPlayerSwitcher extends GameComponent<PKParkourState> {
    private get team() {
        return this.state.team;
    }

    override onAttach(): void {
        this.subscribe(
            Game.events.itemUse,
            (e) => {
                if (e.source.typeId != EntityTypeIds.Player) return;
                const next = this.getNextPlayer(e.source as Player);
                if (next && next.player) {
                    this.switch(e.source, next.player);
                } else {
                    e.source.sendMessage("队伍中没有玩家可以切换了");
                }
            },
            {
                itemId: "minecraft:stick",
                players: this.team,
            }
        );
    }

    /**执行切换操作 */
    private switch(lastPlayer: Player, nextPlayer: Player) {
        //切换前玩家保存物品，改旁观
        const store = this.state.getComponent(PKItemStoreComponent);
        store.storeItem(lastPlayer);
        lastPlayer.setGameMode(GameMode.Spectator);
        lastPlayer.runCommand("clear @s");
        //切换后玩家加载物品，改冒险，tp
        nextPlayer.teleport(lastPlayer.location, {
            dimension: lastPlayer.dimension,
            facingLocation: Vector3Utils.add(
                Vector3Utils.scale(lastPlayer.getViewDirection(), 10),
                lastPlayer.getHeadLocation()
            ),
        });
        nextPlayer.setGameMode(GameMode.Adventure);
        store.loadItem(nextPlayer);
        //提示信息
        this.context.groupSet.sendMessage(
            `§e${lastPlayer.name} §r已将玩家切换到 §e${nextPlayer.name}`
        );
    }

    /** 获取下一个有效玩家，自动跳过离线 */
    private getNextPlayer(player: Player) {
        const idx = this.team.findIndex((p) => p.id === player.id);
        if (idx < 0) return;

        const total = this.team.size;
        if (total === 0) return;

        for (let i = 1; i < total; i++) {
            const nextIndex = (idx + i) % total;
            const candidate = this.team.getAll()[nextIndex];
            if (candidate.isValid) {
                return candidate;
            }
        }

        return undefined;
    }
}
